import React from 'react';
import { Button, Form, Input, Modal, Select, Space, Table } from 'antd'
const { Option } = Select;
//纪念品
const trophy = [
    { id: "1", name: "实物" },
    { id: "2", name: "积分" },
    { id: "3", name: "券码" },
];
function App() {
  const columns = [
        {
            title: "奖品名称",
            dataIndex: "name",
            key: "name",
        },
        {
            title: "奖品数量",
            dataIndex: "amount",
            key: "amount",
        },
        {
            title: "剩余数量",
            dataIndex: "prizeResidue",
            key: "prizeResidue",
        },
        {
            title: "奖品等级",
            key: "level",
            dataIndex: "level",
        },
        {
            title: "中获概率",
            key: "probability",
            dataIndex: "probability",
        },
        {
            title: "奖品类型",
            key: "type_id",
            dataIndex: "type_id",
        },
        {
            title: "操作",
            key: "render",
            render: (_: any, record: AddLuckList) => (//当前行的值，当前行数据，行索引
                <Space size="middle">
                    <Button
                        size="middle"
                        type="primary"
                        onClick={() => changePrize(record)}
                    >
                        编辑
                    </Button>
                    <Button
                        size="middle"
                        type="primary"
                        danger
                        onClick={() => deleteRender(record)}
                    >
                        删除
                    </Button>
                </Space>
            ),
        },
    ];
    const data = [
        {
            // 只能是key
            key: 1,
            name: "奖品1",
            amount: "20",
            prizeResidue: "20",
            level: "3",
            probability: "",
            type_id: "实物",
            score: "",
        },
        {
            key: 2,
            name: "奖品2",
            amount: "30",
            prizeResidue: "30",
            level: "2",
            probability: "",
            type_id: "券码",
            score: ""

        },
    ];
    const [datas, setdatas] = React.useState(data)
    const [isModalOpen, setIsModalOpen] = React.useState(false);
    const [formData] = Form.useForm();
    const [ScoreShow, setScoreShow] = React.useState(false)

    React.useEffect(() => {
        changeProbability(datas)
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [])



    const changeProbability = (datas: AddLuckList[]) => {
        let num: number = 0
        datas.forEach((item) => num += Number(item.prizeResidue))
        let arr = [...datas]

        setdatas(arr.map((item) => {
            return {
                ...item,
                probability: `${(Number(item.prizeResidue) / num * 100).toFixed(2)} % `
            }
        }))
       
    }

    const changePrize = (item: AddLuckList) => {
        console.log(item);
        formData.setFieldsValue({ ...item })
        setScoreShow(item.type_id === "积分" ? true : false)
        setIsModalOpen(true);
    }

    const addPrize = () => {
        setIsModalOpen(true);
    }

    const deleteRender = ({ key }: AddLuckList) => {
        setdatas(datas.filter(item => item.key != key))
       
    }

    const handleOk = () => {
        formData.validateFields().then(() => {
            if (formData.getFieldValue('key')) {
                let data = [...datas]
                data.splice(
                    data.findIndex(item => item.key == formData.getFieldValue('key')),
                    1,
                    {
                        ...formData.getFieldsValue(),
                        prizeResidue: formData.getFieldValue("amount"),
                        key: formData.getFieldValue("key"),
                        probability: "",
                        score: formData.getFieldValue('type_id') == "2" ? formData.getFieldValue('score') : ""
                    }
                )
                changeProbability(data)
            } else {
                let dataAdd = {
                    ...formData.getFieldsValue(),
                    prizeResidue: formData.getFieldValue("amount"),
                    key: datas.length + 1,
                    probability: "",
                    score: formData.getFieldValue('type_id') == "积分" ? formData.getFieldValue('score') : ""
                }
                let dataArr = [...datas, dataAdd]
                changeProbability(dataArr)
            }
            setIsModalOpen(false)
            formData.resetFields();
        })
    };

    const handleCancel = () => {
        setIsModalOpen(false);
        formData.resetFields();
    };

    return (
        <div>
            <div className="basic">奖品设置</div>
            <Table
                columns={columns}
                dataSource={datas}
                style={{ marginTop: "15px" }}
            />
            <Button type="primary" style={{ margin: "auto", display: "block" }} onClick={addPrize}>新增</Button>
            <Modal
                title="Basic Modal"
                open={isModalOpen}
                onOk={handleOk}
                onCancel={handleCancel}
                closable={false}
                bodyStyle={{ width: "350px" }}
                width={380}>
                <Form
                    name="basic"
                    // 允许浏览器输入
                    autoComplete="off"
                    form={formData}
                >
                    <Form.Item
                        label="奖品名称"
                        name="name"
                        rules={[{ required: true, message: '请输入奖品名称!' }]}
                    >
                        <Input size='large' />
                    </Form.Item>
                    <Form.Item
                        label="奖品数量"
                        name="amount"
                        rules={[{ required: true, message: '请输入奖品数量!' }]}
                    >
                        <Input size='large' />
                    </Form.Item>
                    <Form.Item
                        label="奖品等级"
                        name="level"
                        rules={[{ required: true, message: '请输入奖品等级!' }]}
                    >
                        <Input size='large' />
                    </Form.Item>
                    <Form.Item
                        label="奖品类型"
                        name="type_id"
                        rules={[{ required: true, message: '请选择奖品类型!' }]}
                    >
                        <Select
                            onChange={(value: string) => setScoreShow(value === "2" ? true : false)}
                            allowClear
                        >
                            {
                                trophy.map(item => <Option key={item.name} value={item.id}>{item.name}</Option>)
                            }

                        </Select>
                    </Form.Item>
                    {ScoreShow ?
                        <Form.Item
                            label="积分数量"
                            name="score"
                            rules={[{ required: true, message: '请输入积分数量!' }]}
                        >
                            <Input size='large' />
                        </Form.Item> : null
                    }

                </Form>
            </Modal>

        </div>
    )
}

export default App;
